package server;

import java.io.File;
import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Map<String, Host> map;
    private Host defaultHost;
    private Map<String,HttpServlet> servletMap;

    public RequestProcessor(Socket socket, Map<String, Host> map, Host defaultHost) {
        this.socket = socket;
        this.map = map;
        this.defaultHost = defaultHost;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            String requestHost = request.getHost();
            Host host = map.get(requestHost);
            if (host == null) host = defaultHost;
            Wapper wapper = host.getWapper(request);

            // 静态资源处理
            if(wapper == null) {
                String path = host.getDocBase() + File.separator + request.getContext() + request.getUrl();
                response.outputHtml(path);
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = wapper.servlet;
                httpServlet.service(request,response);
            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
